'use client';

import React, { useEffect, useState, useRef, useCallback } from 'react';
import dynamic from 'next/dynamic';

// Dynamically import ForceGraph2D to avoid SSR issues
const ForceGraph2D = dynamic(() => import('react-force-graph-2d'), {
    ssr: false,
    loading: () => <div className="flex items-center justify-center h-full text-ink-medium">Loading Ink...</div>
});

interface WishGraphProps {
    centerId: number;
    depth: number;
}

export default function WishGraph({ centerId, depth }: WishGraphProps) {
    const [graphData, setGraphData] = useState({ nodes: [], links: [] });
    const fgRef = useRef<any>(null);

    useEffect(() => {
        // Fetch graph data
        fetch(`/api/graph?centerId=${centerId}&depth=${depth}`)
            .then(res => res.json())
            .then(data => {
                setGraphData(data);
            })
            .catch(err => console.error("Failed to fetch graph data:", err));
    }, [centerId, depth]);

    const nodeCanvasObject = useCallback((node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
        const label = node.label;
        const fontSize = 12 / globalScale;
        ctx.font = `${fontSize}px "Noto Serif SC", serif`;
        const textWidth = ctx.measureText(label).width;
        const bckgDimensions = [textWidth, fontSize].map(n => n + fontSize * 0.2); // some padding

        // Ink Blob Effect
        ctx.beginPath();
        const r = 5;
        // Simulate rough circle
        ctx.arc(node.x, node.y, r, 0, 2 * Math.PI, false);

        // Style based on group
        if (node.group === 'wish') {
            ctx.fillStyle = node.id === `w-${centerId}` ? '#b91c1c' : 'rgba(26, 26, 26, 0.8)'; // Red for center, Ink for others
        } else {
            ctx.fillStyle = 'rgba(100, 100, 100, 0.6)'; // Lighter for users
        }

        ctx.fill();

        // Text
        ctx.fillStyle = 'rgba(26, 26, 26, 1)';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(label, node.x, node.y + r + fontSize);

        node.__bckgDimensions = bckgDimensions; // to re-use in nodePointerAreaPaint
    }, [centerId]);

    return (
        <div className="w-full h-full absolute inset-0">
            <ForceGraph2D
                ref={fgRef}
                graphData={graphData}
                nodeLabel="label"
                nodeCanvasObject={nodeCanvasObject}
                nodePointerAreaPaint={(node: any, color: string, ctx: CanvasRenderingContext2D) => {
                    ctx.fillStyle = color;
                    const bckgDimensions = node.__bckgDimensions;
                    bckgDimensions && ctx.fillRect(node.x - bckgDimensions[0] / 2, node.y - bckgDimensions[1] / 2, bckgDimensions[0], bckgDimensions[1]);
                }}
                linkColor={() => 'rgba(0, 0, 0, 0.1)'}
                backgroundColor="rgba(0,0,0,0)" // Transparent to show paper texture
                d3VelocityDecay={0.1}
                cooldownTicks={100}
                onEngineStop={() => fgRef.current.zoomToFit(400)}
            />
        </div>
    );
}
